#!/usr/bin/env python
# coding=utf-8
# @FileName :db_client.py
# @Time     :2022/2/16 13:02
# @Author   :ZXC
# @Desc     :
from typing import Union
from loguru import logger

from tools.read_file import ReadFile
from tools.mysql_client import MysqlClient


class PltMysql(object):
    """
    平台MYSQL
    """

    def __init__(self):
        ssh_config = ReadFile.get_config_dict().get('ssh_plt')
        mysql_config = ReadFile.get_config_dict().get('mysql_plt')
        logger.debug(f"开始连接平台mysql数据库。SSH连接信息为：{ssh_config}，MYSQL连接信息为：{mysql_config}")
        self._plt_mysql = MysqlClient(
            host=mysql_config.get('host'),
            port=eval(str(mysql_config.get('port'))),
            user=mysql_config.get('username'),
            password=mysql_config.get('password'),
            db=mysql_config.get('db_name'),
            charset=mysql_config.get('charset'),
            ssh_host=ssh_config.get('host'),
            ssh_port=eval(str(ssh_config.get('port'))),
            ssh_username=ssh_config.get('username'),
            ssh_password=ssh_config.get('password'),
            use_ssh_tunnel=True if eval(str(ssh_config.get('use_ssh'))) != 0 else False
        )
        self._conn = self._plt_mysql.get_conn()

    def close(self):
        logger.debug('正在关闭平台mysql数据库连接')
        self._plt_mysql.close_conn(self._conn)
        self._plt_mysql.close()
        logger.debug('平台mysql数据库连接已关闭')

    def execute_sql(self, sql: str) -> Union[dict, None]:
        if 'select' == sql.split(maxsplit=1)[0].lower():
            logger.info(f'执行mysql查询sql===>{sql}')
            return self._plt_mysql.query_one(self._conn, sql)
        else:
            logger.info(f'执行mysql插入/修改/删除sql===>{sql}')
            return self._plt_mysql.execute_one(self._conn, sql)


class PltTidb(object):
    """
    平台TIDB
    """

    def __init__(self):
        ssh_config = ReadFile.get_config_dict().get('ssh_plt')
        mysql_config = ReadFile.get_config_dict().get('tidb_plt')
        logger.debug(f"开始连接平台TIDB数据库。SSH连接信息为：{ssh_config}，TIDB连接信息为：{mysql_config}")
        self._plt_tidb = MysqlClient(
            host=mysql_config.get('host'),
            port=eval(str(mysql_config.get('port'))),
            user=mysql_config.get('username'),
            password=mysql_config.get('password'),
            db=mysql_config.get('db_name'),
            charset=mysql_config.get('charset'),
            ssh_host=ssh_config.get('host'),
            ssh_port=eval(str(ssh_config.get('port'))),
            ssh_username=ssh_config.get('username'),
            ssh_password=ssh_config.get('password'),
            use_ssh_tunnel=True if eval(str(ssh_config.get('use_ssh'))) != 0 else False
        )
        self._conn = self._plt_tidb.get_conn()

    def close(self):
        logger.debug('正在关闭平台tidb数据库连接')
        self._plt_tidb.close_conn(self._conn)
        self._plt_tidb.close()
        logger.debug('平台tidb数据库连接已关闭')

    def execute_sql(self, sql: str) -> Union[dict, None]:
        if 'select' == sql.split(maxsplit=1)[0].lower():
            logger.info(f'执行tidb查询sql===>{sql}')
            return self._plt_tidb.query_one(self._conn, sql)
        else:
            logger.info(f'执行tidb插入/修改/删除sql===>{sql}')
            return self._plt_tidb.execute_one(self._conn, sql)


mysql_client = None
if ReadFile.read_config('$.mysql_plt').get('use'):
    mysql_client = PltMysql()

tidb_client = None
if ReadFile.read_config('$.tidb_plt').get('use'):
    tidb_client = PltTidb()
